package cn.zk.solution.coder;

import cn.zk.solution.protocol.MessageProtocol;
import cn.zk.solution.server.TcpServerHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

/**
 * 解码器
 */
public class MyMessageDecoder extends ReplayingDecoder<Void> {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("----decoder----");
        MessageProtocol protocol = TcpServerHandler.map.get(ctx.channel().id());
        // 将二进制数据 转为 MessageProtocol对象
        int len = in.readInt();
        byte[] content = new byte[len];
        in.readBytes(content);
        // 封装成MessageProtocol对象
        //MessageProtocol protocol = new MessageProtocol();
        protocol.setLen(len);
        protocol.setContent(content);
        // 放入out，传递给下一个handler处理
        out.add(protocol);
    }
}
